<template>
    <div class="tinymce-editor">
        <Editor
            v-model="myValue"
            :init="init"
            class="mytinyEdit"
            :disabled="disabled"
        >
        </Editor>
    </div>
</template>
<script>
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/preview";
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/media"; // 插入视频插件
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/wordcount"; // 字数统计插件
import './icon/src_common_tinymceIcons'

export default {
    components: {
        Editor
    },
    props: {
        value: {
            type: String,
            default: ""
        },
        // 基本路径，默认为空根目录，如果你的项目发布后的地址为目录形式，
        // 即abc.com/tinymce，baseUrl需要配置成tinymce，不然发布后资源会找不到
        baseUrl: {
            type: String,
            default: ""
        },
        disabled: {
            type: Boolean,
            default: false
        },
        plugins: {
            type: [String, Array],
            default: "lists image media table wordcount"
        },
        toolbar: {
            type: [String, Array],
            default:
                "undo redo | formatselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat | tiny_mce_wiris_formulaEditor | tiny_mce_wiris_formulaEditorChemistry"
        }
    },
    data() {
        return {
            progressBar: 0,
            uploadUrl: "/upload",
            apiUrl: "/upload", //视频文件上传接口
            credentials: true, //凭证
            myValue: this.value,
            tinyLanguage: "",
            tinyLanguage_url: ""
        };
    },
    computed: {
        init() {
            return {
                external_plugins: {
                    tiny_mce_wiris:
                        "https://www.wiris.net/demo/plugins/tiny_mce/plugin.js"
                },
                language_url: this.tinyLanguage_url,
                language: this.tinyLanguage,
                selector: ".mytinyEdit",
                //如果使用的是TinyMCE外观，则可以使用此选项指定外观目录的位置。如果要从一个URL（例如CDN）加载TinyMCE，同时在例如本地服务器上加载外观，则此功能很有用。
                skin_url: `utils/tinymce/skins/ui/oxide`,
                //通常希望TinyMCE的可编辑区域具有与周围内容相同的样式。该content_css选项可实现一致的样式，使您可以将外部CSS扩展到可编辑区域。
                content_css: `utils/tinymce/skins/content/default/content.css`,
                height: 300,
                plugins: this.plugins,
                toolbar: this.toolbar,
                //使用该branding选项可以禁用状态栏中显示的“ 由Tiny提供支持 ”以进行产品归因。
                branding: false,
                //菜单栏
                menubar: false,
                //使用此选项可以禁用Poster媒体对话框中的输入字段。
                media_poster: false,
                media_alt_source: false,
                //通过此选项，您可以使用空格或逗号分隔的类型名称列表来指定所需的文件选择器类型。目前有三种有效的类型：file，image和media。
                file_picker_types: "media",
                //设置paste_data_images为"true"允许粘贴图像，而设置为"false"则不允许粘贴图像。
                paste_data_images: false,
                // 视频上传处理函数
                file_picker_callback: (callback, value, meta) => {
                    //当点击meidia图标上传时,判断meta.filetype == 'media'有必要，因为file_picker_callback是media(媒体)、image(图片)、file(文件)的共同入口
                    if (meta.filetype == "media") {
                        //创建一个隐藏的type=file的文件选择input
                        let input = document.createElement("input");
                        input.setAttribute("type", "file");
                        let that = this;
                        input.onchange = async function() {
                            let file = this.files[0]; //只选取第一个文件
                            let formData = new FormData();
                            formData.append("file", file);
                            let a = document.getElementsByClassName("tox-form");
                            let b = `
                                <div class="first">
                                    <div class="progressBarbox" style='width:0% !important;height:10px !important;background:#207ab7 !important;'></div>
                                    <span class="programNum"></span>
                                </div>`;
                            let c = document.createElement("div");
                            c.innerHTML = b;
                            c.setAttribute("class", "ruoeqri");
                            a[0].appendChild(c);
                            var config = {
                                onUploadProgress: progressEvent => {
                                    let complete =
                                        (((progressEvent.loaded /
                                            progressEvent.total) *
                                            100) |
                                            0) +
                                        "%";
                                    that.changeProgress(
                                        Number(
                                            complete.slice(
                                                0,
                                                complete.length - 1
                                            )
                                        )
                                    );
                                }
                            };
                            let res = await that.$getData(
                                that.uploadUrl,
                                formData,
                                "post",
                                config
                            );
                            if (Number(res.data.code) == 200) {
                                console.log("是否触发");
                                let tempMediaUrl = res.data.entity[0].fileId;
                                let mediaUrl =
                                    process.env.FILE_PRE_SERVER + tempMediaUrl;
                                callback(mediaUrl);
                                let progressBarbox = document.getElementsByClassName(
                                    "progressBarbox"
                                )[0];
                                let programNum = document.getElementsByClassName(
                                    "programNum"
                                )[0];
                                programNum.innerText = 100 + "%";
                                progressBarbox.setAttribute(
                                    "style",
                                    `width: 100% !important;height: 9px !important;background: #207ab7 !important;`
                                );
                            }
                        };
                        //触发点击
                        input.click();
                    }
                },
                //图片上传处理函数
                //此选项允许你使用自定义函数代替TinyMCE来处理上传操作。该自定义函数需提供三个参数：blobInfo、成功回调和失败回调。
                //如果未使用此配置，TinyMCE将使用ajax每次上传一个图片，并在成功返回结果后调用成功回调函数。
                //此函数将完全接管编辑器的图片上传，你需要在上传成功后执行成功回调函数，参数则为图片URL，也可以在第二个参数加入对话框填充数据对象。
                images_upload_handler: async (blobInfo, success) => {
                    let formData = new FormData();
                    formData.append(
                        "file",
                        //官网自带属性，是一个对象，包含图片信息，不知道看官网
                        blobInfo.blob(),
                        blobInfo.filename()
                    );
                    let res = await this.$getData(
                        this.uploadUrl,
                        formData,
                        "post"
                    );
                    if (Number(res.data.code) == 200) {
                        let tempImageUrl = res.data.entity[0].fileId;
                        let imageUrl =
                            process.env.FILE_PRE_SERVER + tempImageUrl;
                        success(imageUrl);
                    }
                }
            };
        }
    },
    watch: {
        value(newValue) {
            this.myValue = newValue;
        },
        myValue(newValue) {
            this.$emit("input", newValue);
        },
        curLanguage: {
            handler(newVal) {
                console.log(newVal, "进入监听", this.init);
                if (newVal == "fr") {
                    (this.tinyLanguage = JSON.parse(JSON.stringify("fr_FR"))),
                        (this.tinyLanguage_url = JSON.parse(
                            JSON.stringify("utils/tinymce/langs/fr_FR.js")
                        ));
                } else if (newVal == "ru") {
                    (this.tinyLanguage = JSON.parse(JSON.stringify("ru"))),
                        (this.tinyLanguage_url = JSON.parse(
                            JSON.stringify("utils/tinymce/langs/ru.js")
                        ));
                } else {
                    (this.tinyLanguage = JSON.parse(JSON.stringify("en"))),
                        (this.tinyLanguage_url = JSON.parse(
                            JSON.stringify("utils/tinymce/langs/en.js")
                        ));
                }
                tinymce.remove()
            },
            immediate: true
        }
    },
    mounted() {
        tinymce.init({});
    },
    methods: {
        clear() {
            this.myValue = "";
        },
        changeProgress(program) {
            console.log("每次调用");
            this.progressBar = program;
            let progressBarbox = document.getElementsByClassName(
                "progressBarbox"
            )[0];
            let programNum = document.getElementsByClassName("programNum")[0];
            let i = 1;
            let j = 1;
            let h = 90;
            if (this.progressBar < 90) {
                progressBarbox.setAttribute(
                    "style",
                    `width: ${this.progressBar}% !important;height: 9px !important;background: #207ab7 !important;`
                );
                programNum.innerText = this.progressBar + "%";
            } else {
                i++;
                if (i > 3) {
                    i = 0;
                    j++;
                }
                h = h + j;
                programNum.innerText = h + "%";
                progressBarbox.setAttribute(
                    "style",
                    `width: ${h}% !important;height: 9px !important;background: #207ab7 !important;`
                );
            }
        }
    }
};
</script>
<style>
.first {
    width: 320px !important;
    height: 10px !important;
    background: #fff !important;
    border: 1px solid #ccc !important;
    position: relative;

}    
.programNum {
    position: absolute;
    right: -46px;
    bottom: -6px;
}
.ruoeqri {
    width: 320px !important;
    height: 10px !important;
    position: absolute !important;
    top: 180px !important;
    left: 110px !important;
    z-index: 999998 !important;
    opacity: 1 !important;
    background: #fff !important;
    border: 1px solid #ccc !important;
}
</style>
